import * as echarts from '../components/ec-canvas/echarts';
import {
  parseTime
} from '../../utils/util';
var config = require('../../script/config.js');
var http = require('../../script/order.js');
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    key: {
      type: Number,
      value: 0
    },
  },
  observers: {
    'key': function (val) {
      if (val != null && val > 0) {
        this.GetData();
      }
    }
  },
  lifetimes: {
    created: function () {
      this.GetData();
    },
    attached: function () {},
    ready: function () {
      this.ecComponent_callTrend = this.selectComponent('#calltrend-chart-dom');
      this.initCallTrendChart();
      this.ecComponent_Servicetype = this.selectComponent('#Servicetype-chart-dom');
      this.initServiceTypeChart();
    },
    detached: function () {
      if (this.chart_callTrend) {
        this.chart_callTrend.dispose();
        this.chart_callTrend = null;
      }
      if (this.chart_Servicetype) {
        this.chart_Servicetype.dispose();
        this.chart_Servicetype = null;
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    /************ 客服概况 ***********/
    SumInfo: {
      DayCallNum: 0,
      DayOrderNum: 0,
      YearCallNum: 0,
      YearOrderNum: 0,
    },
    /************ 客服概况 ***********/

    /************ 近七天来电 ***********/
    ecCallTrend: {
      lazyLoad: true
    },
    CallTrends: [],
    noCallTrendData: false,
    /************ 近七天来电 ***********/

    /************ 来电类型 ***********/
    ecServiceType: {
      lazyLoad: true
    },
    ServiceType: 'channel', // 按渠道channel 按类型type
    ServiceTypes: [],
    ServiceTypeChartData: [],
    noServiceTypeData: false,
    /************ 来电类型 ***********/
    baseUrl: config.baseUrl,
    color: ['#01e1fb', '#00a8ff', '#3270ff', '#40e1d1', '#ff9900', '#ff6600', '#ff0000'],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    GetData() {
      http.GetServiceTotalData().then(res => {
        if (res.code === 200) {
          const CallTotal = res.data.CallTotal; // 客服概览
          const CallTrends = res.data.CallTrends || []; // 近七天来电
          const ServiceTypes = res.data.ServiceTypes || []; // 来电类型
          this.setData({
            SumInfo: {
              DayCallNum: CallTotal ? CallTotal.DayCallNum : 0,
              DayOrderNum: CallTotal ? CallTotal.DayOrderNum : 0,
              YearCallNum: CallTotal ? CallTotal.YearCallNum : 0,
              YearOrderNum: CallTotal ? CallTotal.YearOrderNum : 0,
            },
            CallTrends,
            noCallTrendData: CallTrends.length === 0,
            ServiceTypes,
          });
          this.getServiceTypeData();
        }
      })
    },
    changeServiceType(e) {
      const type = e.currentTarget.dataset.type;
      if (this.data.ServiceType === type) return;
      this.setData({
        ServiceType: type
      });
      this.getServiceTypeData();
    },
    getServiceTypeData() {
      const list = []
      const thisData = this.data.ServiceTypes.find(item => item.TotalType === this.data.ServiceType);
      let listData = {};
      if (thisData && thisData.Data) {
        listData = thisData.Data;
      }
      for (let k in listData) {
        const val = listData[k] ? listData[k] : 0
        list.push({
          name: k,
          value: val
        });
      }
      let total = 0;
      list.forEach(i => {
        total += i.value
      });
      list.forEach(j => {
        j.rate = total === 0 ? 0 : ((j.value / total) * 100).toFixed(2);
      });
      this.setData({
        ServiceTypeChartData: list,
        noServiceTypeData: list.length === 0
      });
      this.setServiceTypeOption();
    },
    initCallTrendChart: function () {
      this.ecComponent_callTrend.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart_callTrend = chart;
        this.setCallTrendChartOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    initServiceTypeChart: function () {
      this.ecComponent_Servicetype.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        this.chart_Servicetype = chart;
        this.setServiceTypeOption();
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
    setCallTrendChartOption() {
      if (!this.chart_callTrend) return;
      if (this.data.CallTrends.length === 0) return;
      let CallNum = [];
      let AnswerNum = [];
      let AnswerRate = [];
      let xData = [];
      for (let i = 0; i < this.data.CallTrends.length; i++) {
        const item = this.data.CallTrends[i];
        CallNum.push(item.CallNum);
        AnswerNum.push(item.AnswerNum);
        AnswerRate.push(item.AnswerRate);
        xData.push(item.CallDate);
      }
      const option = {
        tooltip: {
          trigger: 'axis',
          textStyle: {
            textShadowBlur: 0,
          },
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#f8f8f8'
            }
          },
          // renderMode: 'richText',
          valueFormatter: function (val) {
            return val + " 个";
          },
          confine: true
        },
        legend: {

        },
        grid: {
          top: '50',
          right: '10',
          left: '20',
          bottom: '30',
          containLabel: true,
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            formatter: (val) => {
              return val.slice(5, 10)
            }
          },
          data: xData,
          axisPointer: {
            type: 'shadow'
          }
        }],
        yAxis: [{
            type: 'value',
            name: '数量（个）',
            axisLine: {
              show: true,
            },
            axisLabel: {

            }
          },
          {
            type: 'value',
            name: '%',
            position: 'right',
            axisLine: {
              show: true,
            },
            axisLabel: {

            }
          }
        ],
        series: [{
            name: '总话务量',
            type: 'line',
            data: CallNum,
            // smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            // showSymbol: false,
            itemStyle: {
              color: 'rgba(89,213,241,1)',
              shadowColor: 'rgba(0, 0, 0, 0.5)',
              shadowBlur: 10
            },
            emphasis: {
              focus: 'series'
            },
          },
          {
            name: '应答量',
            type: 'line',
            data: AnswerNum,
            // smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            // showSymbol: false,
            itemStyle: {
              color: 'rgba(247,104,106,1)',
              shadowColor: 'rgba(0, 0, 0, 0.5)',
              shadowBlur: 10
            },
            emphasis: {
              focus: 'series'
            },
          },
          // {
          //   name: '呼出量',
          //   type: 'line',
          //   data: CallOutAmount,
          //   // smooth: true,
          //   symbol: 'circle',
          //   symbolSize: 8,
          //   // showSymbol: false,
          //   itemStyle: {
          //     color: 'rgba(148,119,224,1)',
          //     shadowColor: 'rgba(0, 0, 0, 0.5)',
          //     shadowBlur: 10
          //   },
          //   emphasis: {
          //     focus: 'series'
          //   },
          // },
          {
            name: '应答率',
            type: 'line',
            data: AnswerRate,
            // smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            yAxisIndex:1,
            // showSymbol: false,
            itemStyle: {
              color: 'rgba(255,171,102,1)',
              shadowColor: 'rgba(0, 0, 0, 0.5)',
              shadowBlur: 10
            },
            emphasis: {
              focus: 'series'
            },
            tooltip: {
              valueFormatter: function (val) {
                return val + " %";
              },
            }
          }
        ]
      };
      this.chart_callTrend.setOption(option);
    },
    setServiceTypeOption() {
      if (!this.chart_Servicetype) return;
      if (this.data.ServiceTypeChartData.length === 0) return;
      const option = {
        grid: {
          top: "0",
          left: "10",
          right: "10",
          bottom: "10",
          containLabel: true,
        },
        color: this.data.color,
        title: {
          text: "来电类型",
          top: "middle",
          left: "center",
          textStyle: {
            color: "#606266",
            fontSize: 13,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: 'item',
          valueFormatter: function (val) {
            return val + " 户";
          },
          textStyle: {
            color: "#313131",
            fontSize: 13,
          },
          confine: true,
        },
        legend: {
          show: false,
          orient: "vertical",
          right: "20",
          top: "middle",
          itemWidth: 20,
          itemHeight: 15,
          textStyle: {
            color: "#606266",
            fontSize: 13,
          },
        },
        toolbox: {
          show: false,
        },
        series: {
          name: "来电类型",
          type: "pie",
          clockWise: false,
          radius: ["45%", "70%"],
          center: ["50%", "50%"],
          hoverAnimation: false,
          avoidLabelOverlap: false,
          padAngle: 3,
          label: {
            show: false,
            formatter: "{b|{b}}\n{d|{d}%}",
            rich: {
              b: {
                fontSize: 12,
                color: "#606266",
                align: "left",
                width: "100%",
              },
              d: {
                fontSize: 14,
                color: "#606266",
                align: "left",
              },
            },
          },
          itemStyle: {
            borderRadius: 6,
          },
          data: this.data.ServiceTypeChartData,
        },
      };
      this.chart_Servicetype.setOption(option);
    },
    getLastSevenDays() {
      const today = new Date();
      const dates = [];
      for (let i = 6; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(today.getDate() - i);
        dates.push(parseTime(date, 'yyyy-MM-dd'));
      }
      return dates;
    },
    getDatesOfThisMonth() {
      const dates = [];
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth();
      const todayDate = today.getDate(); // 获取今天是几号

      for (let i = 1; i <= todayDate; i++) {
        const date = new Date(year, month, i);
        dates.push(parseTime(date, 'yyyy-MM-dd'));
      }

      return dates;
    }
  }
})